package com.appspot.etao.service;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import com.appspot.etao.jdo.PMF;
import com.appspot.etao.model.ItemCatModel;
import com.appspot.etao.util.ConvertUtil;
import com.taobao.top.domain.ItemCat;

/**
 * 该程序由GAE自动调度，每天定时执行
 * 将Top上的数据在本地保存副本，已提高页面载入速度
 * 在本地保存数据之前，为了避免数据重复，需要先删除本地数据库中所有已保存的数据
 */
public class CronItemCatService extends BaseService {

	private TopService topService = ServiceFactory.getTopService();
	
	private PersistenceManager pm = PMF.get().getPersistenceManager();

	private void getTopData() {
		System.out.println("CronItemCatService: Start getTopData");
		
		List<ItemCat> itemCatList = topService.getItemCatList();
		List<ItemCatModel> itemCatModelList = ConvertUtil.convertItemCatList(itemCatList);
		pm.makePersistentAll(itemCatModelList);
		
		System.out.println("CronItemCatService: End getTopData");
	}
	
	private void removeLocalData() {
		System.out.println("CronItemCatService: Start removeLocalData");
		
		String itemCatQuery = "select from " + ItemCatModel.class.getName();
		List<ItemCatModel> itemCatModelList = (List<ItemCatModel>)pm.newQuery(itemCatQuery).execute();
		pm.deletePersistentAll(itemCatModelList);
		
		System.out.println("CronItemCatService: End removeLocalData");
	}
	
	/**
	 * 该程序入口
	 * 1. 获取所有Top上的商铺分类，保存到本地
	 */
	public boolean execute(String action) {
		boolean isSuccess = true;
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();

		try {
			tx.begin();
			
			if (action == null || "".equals(action) || "all".equals(action) || "delete".equals(action)) {
				removeLocalData();
			}
			
			if (action == null || "".equals(action) || "all".equals(action) || "insert".equals(action)) {
				getTopData();
			}
			
			tx.commit();
			pm.close();
			
			isSuccess = true;
		} catch (Exception e) {
			e.printStackTrace();
			isSuccess = false;
		} finally {
			if (tx.isActive()) {
				//failure
				System.out.println("FAILURE: No local data should be effected!");
				tx.rollback();
				isSuccess = false;
			} else {
				//success
				System.out.println("SUCCESS: All local data have been updated!");
			}
		}
		return isSuccess;
	}
	
}
